package org.dromara.comm.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.dromara.comm.domain.AsAvatars;
import org.dromara.comm.domain.AsNickName;
import org.dromara.comm.domain.AsUser;
import org.dromara.comm.mapper.AsAvatarsMapper;
import org.dromara.comm.mapper.AsNickNameMapper;
import org.dromara.comm.mapper.AsUserMapper;
import org.dromara.comm.service.AsUserService;
import org.dromara.comm_lhz.util.QiniuUtil;
import org.dromara.system.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 小程序登录控制层
 *
 * @author: 郭伟明
 * @date: 2024-08-07 11:45
 **/
@RestController
@RequestMapping("/user")
@Tag(name = "小程序登录")
public class AsUserController {

    @Autowired
    private AsUserService asUserService;

    @Autowired
    private AsUserMapper asUserMapper;

    @Autowired
    QiniuUtil qiniuUtil;

    @Autowired
    private AsNickNameMapper asNickNameMapper;

    @Autowired
    private AsAvatarsMapper asAvatarsMapper;

//    @SaIgnore
//    @Operation(summary = "小程序登录")
//    @PostMapping(value = "/logins")
//    public Map<String,Object> login(@RequestBody AsUser asUser){
//        Map<String, Object> hashMap = new HashMap<>();
//        Map<String, Object> login = asUserService.login(asUser);
//        hashMap.put("status",login);
//        hashMap.put("success",200);
//        return hashMap;
//    }



    @SaIgnore
    @Operation(summary = "小程序注册")
    @PostMapping("/register")
    public void register(@RequestBody SysUser sysUser) {
        asUserService.register(sysUser);
    }


    @SaIgnore
    @Operation(summary = "修改资料")
    @PostMapping("/uploadUser")
    public ResponseEntity<Map<String, Object>> uploadImageAsParty(
        @RequestParam(value = "file", required = false) MultipartFile file,
        @RequestParam(value = "id") Long id,
        @RequestParam(value = "username", required = false) String username,
        @RequestParam(value = "avatar", required = false) String avatar) {

        Map<String, Object> response = new HashMap<>();

        try {
            // 根据ID查找党建，确认党建存在。
            AsUser asUser = asUserMapper.selectById(id);
            if (asUser == null) {
                response.put("message", "党建未找到");
                return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
            }

            // 如果上传了图片，进行图片上传并更新党建的图片URL。
            String imageUrl = null;
            if (file != null && !file.isEmpty()) {
                imageUrl = qiniuUtil.uploadImage(file);
                asUser.setAvatar(imageUrl);  // 更新图片 URL
            }

            // 更新党建的其他信息。
            if (username != null) asUser.setUsername(username);
            if (avatar != null) asUser.setAvatar(avatar);

            // 保存更新后的党建信息。确保使用更新方法而不是插入方法。
            asUserMapper.updateById(asUser);

            // 组装并返回更新成功的响应信息，包括图片URL。
            response.put("message", "资料修改成功");
            response.put("imageUrl", imageUrl);
            return new ResponseEntity<>(response, HttpStatus.OK);

        } catch (Exception e) {
            response.put("message", "发生错误：" + e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @SaIgnore
    @Operation(summary = "获取随机昵称和头像")
    @GetMapping("/randomNickName")
    private ResponseEntity<Map<String, Object>> getRandomNickName() {
        Map<String, Object> hashMap = new HashMap<>();
        AsNickName asNickName = asNickNameMapper.selectRandomNickName();
        AsAvatars randomAvatars = asAvatarsMapper.selectRandomAvatars();
        hashMap.put("nickName", asNickName);
        hashMap.put("avatar", randomAvatars);
        return ResponseEntity.ok(hashMap) ;
    }

    @SaIgnore
    @PostMapping("/miniProgramLogin")
    public ResponseEntity<Map<String,String>> miniProgramLogin(@RequestBody SysUser sysUser) {
        // 验证用户信息
        SysUser isAuthenticated = authenticateUser(sysUser);

        if (isAuthenticated != null) {
            // 生成 Token 并存储
            return ResponseEntity.ok(asUserService.createToken(sysUser));
        } else {
            throw new SecurityException("Authentication failed");
        }
    }

    private SysUser authenticateUser(SysUser sysUser) {
        SysUser sysUsers = asUserMapper.loadUserByUsername(sysUser);
        if (sysUsers==null) {
            throw new RuntimeException("空数据");
        }
        if (sysUser.getUserName()!=null && sysUser.getPassword()!=null){
            return sysUsers;
        }else {
            return null;
        }
    }

}
